package com.newlink.building.common_base.utils

import android.graphics.Bitmap
import android.graphics.Color
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.MultiFormatWriter
import com.google.zxing.WriterException
import com.google.zxing.common.BitMatrix
import java.util.*

/**
 * Created by xiaodong on 2022/10/2.
 */
object QRCodeUtils {
    //生成二维码图片（不带图片）
    @Throws(WriterException::class)
    fun createQRCode(url: String?, widthAndHeight: Int): Bitmap? {
        val hints = Hashtable<EncodeHintType, Any?>()
        hints[EncodeHintType.CHARACTER_SET] = "utf-8"
        hints[EncodeHintType.MARGIN] = 0
        val matrix: BitMatrix = MultiFormatWriter().encode(
            url,
            BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight, hints
        )
        val width: Int = matrix.width
        val height: Int = matrix.height
        val pixels = IntArray(width * height)
        //画黑点
        for (y in 0 until height) {
            for (x in 0 until width) {
                if (matrix.get(x, y)) {
                    pixels[y * width + x] = Color.BLACK //0xff000000
                }
            }
        }
        val bitmap = Bitmap.createBitmap(
            width, height,
            Bitmap.Config.ARGB_8888
        )
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height)
        return bitmap
    }
}